package controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.LinkedList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class RequestParameterFilter
 */
@WebFilter (filterName="/RequestParameterFilter", urlPatterns={"/*"})
public class RequestParameterFilter implements Filter {

	private LinkedList<String> allowedParams;
	private String[] parameters = {"id","add","edit",
			"film_tytul","film_rok","film_rezyser","rezyser_imie","rezyser_nazwisko"};
	private int max_length;
	
    /**
     * Default constructor. 
     */
    public RequestParameterFilter() {
    	allowedParams = new LinkedList<String>();
    	for(String s:parameters)
    	{
    		allowedParams.add(s);
    	}
    	max_length = allowedParams.size();
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		Enumeration<String> p = req.getParameterNames();
		int counter = 0;
		while(p.hasMoreElements())
		{
			String param = p.nextElement();
			System.out.println("Parametr: "+param);
			counter++;
			
			if(counter>max_length || !allowedParams.contains(param))
			{
				System.out.println("Blad");
				
				RequestDispatcher dispatcher = 
			    		req.getServletContext().getRequestDispatcher ("/loginQueryView.jsp"); 
			    dispatcher.forward(req, resp);
			    
			    req.logout();
			    
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
